package com.example.network.demos.tcp.client.dongzong;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;


/**
 * Netty 客户端处理器类，继承自 SimpleChannelInboundHandler<String> 以处理服务器发送的字符串数据
 *
 * @author chenlei
 */
@ChannelHandler.Sharable // 确保可以被多个 channel 共享
@Slf4j
public class NettyTcpClientHandlerDongzong extends SimpleChannelInboundHandler<String> {

    private final Bootstrap bootstrap;

    private final String host;

    private final int port;

    private final NettyTcpClientDongzong client;

    public NettyTcpClientHandlerDongzong(Bootstrap bootstrap, String host, int port, NettyTcpClientDongzong client) {
        this.bootstrap = bootstrap;
        this.host = host;
        this.port = port;
        this.client = client;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        log.info("收到消息：{}", msg);
        // 处理接收的消息
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.warn("连接断开，即将尝试重新连接...");
        // 使用 eventLoop 延迟执行重连，防止频繁连接
        ctx.channel().eventLoop().schedule(() -> {
            client.reconnect(bootstrap, host, port);
        }, 5, TimeUnit.SECONDS); // 延迟5秒后重连
        super.channelInactive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("发生异常", cause);
        ctx.close(); // 关闭连接，触发 channelInactive
    }
}
